package com.ruov.plugin.wx.offiaccount.utils;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSONObject;
import com.ruov.plugin.wx.offiaccount.entity.res.WxQRCodeRes;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import org.springframework.stereotype.Component;

/**
 * @author wjsmc
 * @date 2025/4/24 11:31
 * @description
 **/

@Component
@Slf4j
@AllArgsConstructor
public class WxQrCodeUtils {

    private final WxMpService wxMpService;

    /**
     * 生成微信临时二维码
     *
     * @param expireSeconds 二维码有效期（秒）
     * @return 接口响应JSON字符串
     */
    public WxQRCodeRes createTempQRCode(String sceneStr, Long expireSeconds) {
        String url;
        try {
            url = String.format(
                    "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=%s",
                    wxMpService.getAccessToken()
            );
        } catch (WxErrorException e) {
            log.error("获取微信access_token失败", e);
            throw new RuntimeException(e);
        }
        JSONObject requestBody = new JSONObject();
        requestBody.put("expire_seconds", expireSeconds);
        requestBody.put("action_name", "QR_STR_SCENE");

        JSONObject scene = new JSONObject();
        if (sceneStr != null) {
            scene.put("scene_str", sceneStr);
        }

        JSONObject actionInfo = new JSONObject();
        if (!scene.isEmpty()) {
            actionInfo.put("scene", scene);
        }
        requestBody.put("action_info", actionInfo);
        try (HttpResponse response = HttpRequest.post(url)
                .header("Content-Type", "application/json")
                .body(requestBody.toString())
                .execute()) {
            return JSONUtil.toBean(response.body(), WxQRCodeRes.class);
        }
    }
}
